<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha256-wiz7ZSCn/btzhjKDQBms9Hx4sSeUYsDrTLg7roPstac=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.css" integrity="sha256-6cQIC71/iBIYXFK+0RHAvwmjwWzkWd+r7v/BX3/vZDc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"sumumm.github.io","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.19.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":true,"height":300},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文主要是字符设备驱动开发实例的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:type" content="article">
<meta property="og:title" content="LV10-02-字符设备驱动-04-字符设备开发实例">
<meta property="og:url" content="https://sumumm.github.io/post/5a7bd00a.html">
<meta property="og:site_name" content="苏木">
<meta property="og:description" content="本文主要是字符设备驱动开发实例的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-07-08T10:58:13.000Z">
<meta property="article:modified_time" content="2025-06-13T16:25:57.003Z">
<meta property="article:author" content="苏木">
<meta property="article:tag" content="LV10-驱动开发">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://sumumm.github.io/post/5a7bd00a.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://sumumm.github.io/post/5a7bd00a.html","path":"post/5a7bd00a.html","title":"LV10-02-字符设备驱动-04-字符设备开发实例"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>LV10-02-字符设备驱动-04-字符设备开发实例 | 苏木</title>
  








    <script src="/js/browser_tools_disable.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<!-- hexo injector head_end start --><link rel="stylesheet" href="https://unpkg.com/hexo-next-tags-plus@latest/lib/tag_plus.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">苏木</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">我的学习之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>苏木的家</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类页<span class="badge">42</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档页<span class="badge">673</span></a></li><li class="menu-item menu-item-flink"><a href="/flink/" rel="section"><i class="fa fa-link fa-fw"></i>友人帐</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E5%8D%95%E4%B8%AA%E6%AC%A1%E8%AE%BE%E5%A4%87"><span class="nav-text">一、单个次设备</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%BC%80%E5%8F%91%E6%AD%A5%E9%AA%A4"><span class="nav-text">1. 开发步骤</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%BC%80%E5%8F%91%E5%AE%9E%E4%BE%8B"><span class="nav-text">2. 开发实例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-new-char-dev-c"><span class="nav-text">2.1 new_char_dev.c </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-new-char-dev-h"><span class="nav-text">2.2 new_char_dev.h </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-app-new-char-dev-c"><span class="nav-text">2.3 app_new_char_dev.c </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-Makefile"><span class="nav-text">2.4 Makefile </span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%A4%9A%E4%B8%AA%E6%AC%A1%E8%AE%BE%E5%A4%87"><span class="nav-text">二、多个次设备</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%BC%80%E5%8F%91%E6%AD%A5%E9%AA%A4-1"><span class="nav-text">1. 开发步骤</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%BC%80%E5%8F%91%E5%AE%9E%E4%BE%8B-1"><span class="nav-text">2. 开发实例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-new-char-dev-multi-c"><span class="nav-text">2.1 new_char_dev_multi.c </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-new-char-dev-multi-h"><span class="nav-text">2.2 new_char_dev_multi.h </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-app-new-char-dev-multi-c"><span class="nav-text">2.3 app_new_char_dev_multi.c </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-4-Makefile-1"><span class="nav-text">2.4 Makefile </span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="苏木"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">苏木</p>
  <div class="site-description" itemprop="description">莫道桑榆晚，为霞尚满天</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">673</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">42</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">43</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/sumumm" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sumumm" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://sumumm.github.io/post/5a7bd00a.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="苏木">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏木">
      <meta itemprop="description" content="莫道桑榆晚，为霞尚满天">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="LV10-02-字符设备驱动-04-字符设备开发实例 | 苏木">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          LV10-02-字符设备驱动-04-字符设备开发实例
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-07-08 18:58:13" itemprop="dateCreated datePublished" datetime="2023-07-08T18:58:13+08:00">2023-07-08</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">嵌入式开发</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/" itemprop="url" rel="index"><span itemprop="name">01HQ课程体系</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV10-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">LV10-驱动开发</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>6.7k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>24 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本文主要是字符设备驱动开发实例的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。</p>
<span id="more"></span>

<!-- Photo: https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV10-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/LV10-02-%E5%AD%97%E7%AC%A6%E8%AE%BE%E5%A4%87%E9%A9%B1%E5%8A%A8-04-%E5%AD%97%E7%AC%A6%E8%AE%BE%E5%A4%87%E5%BC%80%E5%8F%91%E5%AE%9E%E4%BE%8B/img/ -->

<details class="folding-tag" blue><summary> 点击查看使用工具及版本 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150px>Windows</td>        <td align="left">windows11</td>    </tr>    <tr>        <td align="center">Ubuntu</td>        <td align="left">Ubuntu16.04的64位版本</td>      </tr>    <tr>        <td align="center">VMware® Workstation 16 Pro</td>        <td align="left">16.2.3 build-19376536</td>      </tr>    <tr>        <td align="center">SecureCRT</td>        <td align="left">Version 8.7.2 (x64 build 2214)   -   正式版-2020年5月14日</td>      </tr>    <tr>        <td align="center" width=150>Linux开发板</td>        <td align="left">华清远见 底板: FS4412_DEV_V5 核心板: FS4412 V2</td>      </tr>    <tr>        <td align="center" width=150>u-boot</td>        <td align="left">2013.01</td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看本文参考资料 </summary>
              <div class='content'>
              <table>    <tr><td align="center">参考方向  </td><td align="center">参考原文</td></tr>    <tr><td align="left">---</td><td align="left"><a href="" target="_blank">--- <i class="fa fa-external-link-alt"></i> </a></td></tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看相关文件下载 </summary>
              <div class='content'>
              <table>    <tr><td align="center">文件</td><td align="center">下载链接</td></tr>    <tr><td align="left">---</td><td align="left"><a href="https://wwz.lanzouy.com/iH1vO09jxavi" target="_blank">--- <i class="fa fa-external-link-alt"></i> </a></td></tr></table>
              </div>
            </details>

<h1 id="一、单个次设备"><a href="#一、单个次设备" class="headerlink" title="一、单个次设备"></a><font size=3>一、单个次设备</font></h1><h2 id="1-开发步骤"><a href="#1-开发步骤" class="headerlink" title="1. 开发步骤"></a><font size=3>1. 开发步骤</font></h2><p>字符设备驱动基本开发步骤如下：</p>
<ul>
<li>1、如果设备有自己的一些控制数据，则定义一个包含 <code>struct cdev mydev</code> 成员的结构体 <code>struct __my_dev</code> ，其它成员根据设备需求，设备简单则直接用 <code>struct cdev </code>。</li>
<li>2、定义一个 <code>struct mydev</code> 或 <code>struct cdev</code> 的全局变量来表示本设备；也可以定义一个 <code>struct __my__dev</code> 或 <code>struct cdev</code> 的全局指针（需要在 <code>init</code> 时动态分配）。</li>
<li>3、定义三个全局变量分别来表示主设备号、次设备号、设备数（只有一个次设备的话也可以写进 <code>struct __my__dev</code> 结构体中）。</li>
<li>4、定义一个 <code>struct file_operations</code> 结构体变量，其 <code>owner</code> 成员置成 <code>THIS_MODULE</code> 。</li>
<li>5、 <code>module init</code> 函数流程：</li>
</ul>
<p>（1）申请设备号；</p>
<p>（2）如果是全局设备指针则动态分配代表本设备的结构体元素 ；</p>
<p>（3）初始化 <code>struct cdev</code> 成员；</p>
<p>（4）设置 <code>struct cdev</code> 的 <code>owner</code> 成员为 <code>THIS_MODULE</code> ；</p>
<p>（5）添加字符设备到内核；</p>
<p>（6）创建类；</p>
<p>（7）创建设备；</p>
<ul>
<li>6、 <code>module exit</code> 函数流程：</li>
</ul>
<p>（1）删除设备；</p>
<p>（2）删除类；</p>
<p>（3）注销设备号；</p>
<p>（4）从内核中移除 <code>struct cdev</code>  ；</p>
<p>（5）如果是全局设备指针则释放其指向空间.</p>
<ul>
<li>7、编写各个操作函数并将函数名初始化给 <code>struct file_operations</code> 结构体变量。</li>
</ul>
<h2 id="2-开发实例"><a href="#2-开发实例" class="headerlink" title="2. 开发实例"></a><font size=3>2. 开发实例</font></h2><h3 id="2-1-new-char-dev-c"><a href="#2-1-new-char-dev-c" class="headerlink" title="2.1 new_char_dev.c "></a><font size=3>2.1 new_char_dev.c </font></h3><details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** =====================================================</span></span><br><span class="line"><span class="comment"> * Copyright © hk. 2022-2025. All rights reserved.</span></span><br><span class="line"><span class="comment"> * File name: new_char_dev.c</span></span><br><span class="line"><span class="comment"> * Author   : qidaink</span></span><br><span class="line"><span class="comment"> * Date     : 2022-08-24</span></span><br><span class="line"><span class="comment"> * Version  :</span></span><br><span class="line"><span class="comment"> * Description: 新字符设备开发框架——单个次设备</span></span><br><span class="line"><span class="comment"> * Others   :</span></span><br><span class="line"><span class="comment"> * Log      :</span></span><br><span class="line"><span class="comment"> * ======================================================</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">//=======================================================</span></span><br><span class="line"><span class="comment">/* 头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/module.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/kernel.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/fs.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/cdev.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;asm/uaccess.h&gt;</span>   <span class="comment">/* copy_from_user copy_to_user  */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/device.h&gt;</span>  <span class="comment">/* class_create class_destroy device_create */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;new_char_dev.h&quot;</span></span></span><br><span class="line"><span class="comment">//=======================================================</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> NEWCHRLED_NAME <span class="string">&quot;new_char_dev&quot;</span> <span class="comment">/* 设备名称： /proc/devices 文件中与该设备对应的名字，方便用户层查询主设备号 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> BUF_LEN 100                   <span class="comment">/* 数据读写缓冲区大小 */</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 新字符设备的属性 */</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="comment">/* 1.设备号与设备数量 */</span></span><br><span class="line">    <span class="type">int</span> major;    <span class="comment">/* 主设备号：占高12位，用来表示驱动程序相同的一类设备，Linux系统中主设备号范围为 0~4095 */</span></span><br><span class="line">    <span class="type">int</span> minor;    <span class="comment">/* 次设备号：占低20位，用来表示被操作的哪个具体设备 */</span></span><br><span class="line">    <span class="type">dev_t</span> devno;  <span class="comment">/* 新字符设备的设备号：由主设备号和次设备号组成     */</span></span><br><span class="line">    <span class="type">int</span> dev_num;  <span class="comment">/* 申请的设备数量 */</span></span><br><span class="line">    <span class="comment">/* 2.字符设备对象 */</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">cdev</span> <span class="title">mydev</span>;</span>       <span class="comment">/* 定义一个字符设备对象设备 */</span></span><br><span class="line">    <span class="comment">/* 3.设备读写相关成员变量 */</span></span><br><span class="line">    <span class="type">char</span> mydev_buf[BUF_LEN]; <span class="comment">/* 读写缓冲区 */</span></span><br><span class="line">    <span class="type">int</span> curlen;              <span class="comment">/* 读写缓冲区中当前数据字节数 */</span></span><br><span class="line">    <span class="comment">/* 4.自动创建设备节点相关成员变量 */</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="keyword">class</span> *<span class="keyword">class</span>;</span>     <span class="comment">/* 类 */</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">device</span> *<span class="title">device</span>;</span>   <span class="comment">/* 设备 /dev/dev_name */</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span> <span class="title">g_my_dev</span>;</span>     <span class="comment">/* 定义一个新字符设备 */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//=======================================================</span></span><br><span class="line"><span class="comment">/* 新字符设备操作函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">mydev_open</span><span class="params">(<span class="keyword">struct</span> inode *pnode, <span class="keyword">struct</span> file *pfile)</span>;                                      <span class="comment">/* 打开设备 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">mydev_close</span><span class="params">(<span class="keyword">struct</span> inode *pnode, <span class="keyword">struct</span> file *pfile)</span>;                                     <span class="comment">/* 关闭设备 */</span></span><br><span class="line"><span class="type">ssize_t</span> <span class="title function_">mydev_read</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">char</span> __user *pbuf, <span class="type">size_t</span> count, <span class="type">loff_t</span> *ppos)</span>;        <span class="comment">/* 读设备 */</span></span><br><span class="line"><span class="type">ssize_t</span> <span class="title function_">mydev_write</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">const</span> <span class="type">char</span> __user *pbuf, <span class="type">size_t</span> count, <span class="type">loff_t</span> *ppos)</span>; <span class="comment">/* 写设备 */</span></span><br><span class="line"><span class="type">long</span> <span class="title function_">mydev_ioctl</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">unsigned</span> <span class="type">int</span> cmd, <span class="type">unsigned</span> <span class="type">long</span> arg)</span>;                    <span class="comment">/* 设备属性获取 */</span></span><br><span class="line"><span class="comment">/* 操作函数集定义 */</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">file_operations</span> <span class="title">myops</span> =</span> &#123;</span><br><span class="line">    <span class="comment">/* data */</span></span><br><span class="line">    .owner = THIS_MODULE,</span><br><span class="line">    .open = mydev_open,</span><br><span class="line">    .release = mydev_close,</span><br><span class="line">    .read = mydev_read,</span><br><span class="line">    .write = mydev_write,</span><br><span class="line">    .unlocked_ioctl = mydev_ioctl,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * @Function    : mydev_open</span></span><br><span class="line"><span class="comment"> * @brief       : 打开设备</span></span><br><span class="line"><span class="comment"> * @param pnode : struct inode * 类型，内核中记录文件元信息的结构体</span></span><br><span class="line"><span class="comment"> * @param pfile : struct file *  类型，读写文件内容过程中用到的一些控制性数据组合而成的对象</span></span><br><span class="line"><span class="comment"> * @return      : 0,操作完成</span></span><br><span class="line"><span class="comment"> * @Description : 函数名初始化给 struct file_operations 的成员 .open</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">mydev_open</span><span class="params">(<span class="keyword">struct</span> inode *pnode, <span class="keyword">struct</span> file *pfile)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">/* 获取 struct _my_dev g_my_dev 地址 */</span></span><br><span class="line">    pfile-&gt;private_data = (<span class="type">void</span> *)(container_of(pnode-&gt;i_cdev, <span class="keyword">struct</span> _my_dev, mydev));</span><br><span class="line">    printk(<span class="string">&quot;mydev_open is called!\n&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * @Function    : mydev_close</span></span><br><span class="line"><span class="comment"> * @brief       : 关闭设备</span></span><br><span class="line"><span class="comment"> * @param pnode : struct inode * 类型，内核中记录文件元信息的结构体</span></span><br><span class="line"><span class="comment"> * @param pfile : struct file *  类型，读写文件内容过程中用到的一些控制性数据组合而成的对象</span></span><br><span class="line"><span class="comment"> * @return      : 0,操作完成</span></span><br><span class="line"><span class="comment"> * @Description : 函数名初始化给 struct file_operations 的成员 .close</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">mydev_close</span><span class="params">(<span class="keyword">struct</span> inode *pnode, <span class="keyword">struct</span> file *pfile)</span></span><br><span class="line">&#123;</span><br><span class="line">    printk(<span class="string">&quot;mydev_close is called!\n&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * @Function    : mydev_read</span></span><br><span class="line"><span class="comment"> * @brief       : 读设备</span></span><br><span class="line"><span class="comment"> * @param pfile : struct file *  类型，指向open产生的struct file类型的对象，表示本次read对应的那次open。</span></span><br><span class="line"><span class="comment"> *                                    (读写文件内容过程中用到的一些控制性数据组合而成的对象)</span></span><br><span class="line"><span class="comment"> * @param pbuf  ：__user * 类型，指向用户空间一块内存，用来保存读到的数据。</span></span><br><span class="line"><span class="comment"> * @param count ：size_t   类型，用户期望读取的字节数。</span></span><br><span class="line"><span class="comment"> * @param ppos  ：loff_t * 类型，对于需要位置指示器控制的设备操作有用，用来指示读取的起始位置，读完后也需要变更位置指示器的指示位置。</span></span><br><span class="line"><span class="comment"> * @return      : 成功返回本次成功读取的字节数，失败返回-1</span></span><br><span class="line"><span class="comment"> * @Description : 函数名初始化给 struct file_operations 的成员 .read</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">ssize_t</span> <span class="title function_">mydev_read</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">char</span> __user *pbuf, <span class="type">size_t</span> count, <span class="type">loff_t</span> *ppos)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> size = <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span> *<span class="title">p_my_dev</span> =</span> (<span class="keyword">struct</span> _my_dev *)(pfile-&gt;private_data);</span><br><span class="line">    <span class="keyword">if</span> (count &gt; p_my_dev-&gt;curlen)</span><br><span class="line">        size = p_my_dev-&gt;curlen;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        size = count;</span><br><span class="line">    ret = copy_to_user(pbuf, p_my_dev-&gt;mydev_buf, size);</span><br><span class="line">    <span class="keyword">if</span> (ret)</span><br><span class="line">    &#123;</span><br><span class="line">        printk(<span class="string">&quot;copy to user buf failed!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">memcpy</span>(p_my_dev-&gt;mydev_buf, p_my_dev-&gt;mydev_buf + size, p_my_dev-&gt;curlen - size);</span><br><span class="line">    p_my_dev-&gt;curlen -= size;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> size;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * @Function    : mydev_write</span></span><br><span class="line"><span class="comment"> * @brief       : 写设备</span></span><br><span class="line"><span class="comment"> * @param pfile : struct file *  类型，指向open产生的struct file类型的对象，表示本次write对应的那次open。</span></span><br><span class="line"><span class="comment"> *                                    (读写文件内容过程中用到的一些控制性数据组合而成的对象)</span></span><br><span class="line"><span class="comment"> * @param pbuf  ：__user * 类型，指向用户空间一块内存，用来保存被写的数据。</span></span><br><span class="line"><span class="comment"> * @param count ：size_t   类型，用户期望写入的字节数。</span></span><br><span class="line"><span class="comment"> * @param ppos  ：loff_t * 类型，对于需要位置指示器控制的设备操作有用，用来指示写入的起始位置，写完后也需要变更位置指示器的指示位置。</span></span><br><span class="line"><span class="comment"> * @return      : 成功返回本次成功写入的字节数，失败返回-1</span></span><br><span class="line"><span class="comment"> * @Description : 函数名初始化给 struct file_operations 的成员 .write</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">ssize_t</span> <span class="title function_">mydev_write</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">const</span> <span class="type">char</span> __user *pbuf, <span class="type">size_t</span> count, <span class="type">loff_t</span> *ppos)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> size = <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span> *<span class="title">p_my_dev</span> =</span> (<span class="keyword">struct</span> _my_dev *)(pfile-&gt;private_data);</span><br><span class="line">    <span class="keyword">if</span> (count &gt; BUF_LEN - p_my_dev-&gt;curlen)</span><br><span class="line">        size = BUF_LEN - p_my_dev-&gt;curlen;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        size = count;</span><br><span class="line">    ret = copy_from_user(p_my_dev-&gt;mydev_buf + p_my_dev-&gt;curlen, pbuf, size);</span><br><span class="line">    <span class="keyword">if</span> (ret)</span><br><span class="line">    &#123;</span><br><span class="line">        printk(<span class="string">&quot;copy from user buf failed!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    p_my_dev-&gt;curlen += size;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> size;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * @Function    : mydev_ioctl</span></span><br><span class="line"><span class="comment"> * @brief       : 设备属性获取</span></span><br><span class="line"><span class="comment"> * @param pfile : struct file *  类型，指向open产生的struct file类型的对象，表示本次ioctl对应的那次open。</span></span><br><span class="line"><span class="comment"> *                                    (读写文件内容过程中用到的一些控制性数据组合而成的对象)</span></span><br><span class="line"><span class="comment"> * @param cmd   ：unsigned int  类型，用来表示做的是哪一个操作。</span></span><br><span class="line"><span class="comment"> * @param arg   ：unsigned long 类型，和cmd配合用的参数。</span></span><br><span class="line"><span class="comment"> * @return      : 成功返回0，失败返回-1</span></span><br><span class="line"><span class="comment"> * @Description : 函数名初始化给 struct file_operations 的成员 .unlocked_ioctl</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">long</span> <span class="title function_">mydev_ioctl</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">unsigned</span> <span class="type">int</span> cmd, <span class="type">unsigned</span> <span class="type">long</span> arg)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> __user *pret = (<span class="type">int</span> *)arg;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span> *<span class="title">p_my_dev</span> =</span> (<span class="keyword">struct</span> _my_dev *)(pfile-&gt;private_data);</span><br><span class="line">    <span class="type">int</span> maxlen = BUF_LEN;</span><br><span class="line">    <span class="keyword">switch</span> (cmd)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">case</span> MYCHAR_IOCTL_GET_MAXLEN:</span><br><span class="line">            <span class="keyword">if</span> (copy_to_user(pret, &amp;maxlen, <span class="keyword">sizeof</span>(<span class="type">int</span>)))</span><br><span class="line">            &#123;</span><br><span class="line">                printk(<span class="string">&quot;copy_to_user maxlen failed!\n&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> MYCHAR_IOCTL_GET_CURLEN:</span><br><span class="line">            <span class="keyword">if</span> (copy_to_user(pret, &amp;p_my_dev-&gt;curlen, <span class="keyword">sizeof</span>(<span class="type">int</span>)))</span><br><span class="line">            &#123;</span><br><span class="line">                printk(<span class="string">&quot;copy_to_user curlen failed!\n&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            printk(<span class="string">&quot;The cmd is unknown!\n&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 驱动入口函数 */</span></span><br><span class="line"><span class="type">int</span> __init <span class="title function_">new_char_dev_init</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">/* 1.分配设备号 */</span></span><br><span class="line">    g_my_dev.major = <span class="number">200</span>;                                   <span class="comment">/* 手动指定主设备号 */</span></span><br><span class="line">    g_my_dev.minor = <span class="number">0</span>;                                     <span class="comment">/* 大部分驱动次设备号都选择0 */</span></span><br><span class="line">    g_my_dev.dev_num = <span class="number">1</span>;                                   <span class="comment">/* 申请的设备数量 */</span></span><br><span class="line">    g_my_dev.devno = MKDEV(g_my_dev.major, g_my_dev.minor); <span class="comment">/* MKDEV宏用来将主设备号和次设备号组合成32位完整的设备号 */</span></span><br><span class="line">    <span class="keyword">if</span> (register_chrdev_region(g_my_dev.devno, g_my_dev.dev_num, NEWCHRLED_NAME))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* 手动指定设备号分配失败，申请自动分配设备号 */</span></span><br><span class="line">        <span class="keyword">if</span> (alloc_chrdev_region(&amp;g_my_dev.devno, <span class="number">0</span>, g_my_dev.dev_num, NEWCHRLED_NAME))</span><br><span class="line">        &#123;</span><br><span class="line">            printk(<span class="string">&quot;get devno failed!\n&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">/* 重新获取主设备号和次设备号 */</span></span><br><span class="line">        g_my_dev.major = MAJOR(g_my_dev.devno); <span class="comment">/* 自动分配设备号后，分离出主设备号 */</span></span><br><span class="line">        g_my_dev.minor = MINOR(g_my_dev.minor); <span class="comment">/* 自动分配设备号后，分离出次设备号 */</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 2.向Linux内核注册新的字符设备 */</span></span><br><span class="line">    <span class="comment">/* 2.1初始化 mydev 对象, 给该对象添加操作函数集 */</span></span><br><span class="line">    cdev_init(&amp;g_my_dev.mydev, &amp;myops);</span><br><span class="line">    <span class="comment">/* 2.2向 Linux 系统添加字符设备 (cdev结构体变量,将会被添加到一个hash链表中) */</span></span><br><span class="line">    g_my_dev.mydev.owner = THIS_MODULE;</span><br><span class="line">    cdev_add(&amp;g_my_dev.mydev, g_my_dev.devno, g_my_dev.dev_num); <span class="comment">/* 会在 /proc/devices 中创建设备号和对应的名称记录 */</span></span><br><span class="line">    <span class="comment">/* 3.自动创建设备节点(省去 mknod 命令在 /dev 下创建设备节点步骤) */</span></span><br><span class="line">    <span class="comment">/* 3.1创建类 */</span></span><br><span class="line">    g_my_dev.class = class_create(THIS_MODULE, NEWCHRLED_NAME);</span><br><span class="line">    <span class="keyword">if</span> (IS_ERR(g_my_dev.class))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> PTR_ERR(g_my_dev.class);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 3.2创建设备(创建的设备为 /dev/dev_name) */</span></span><br><span class="line">    g_my_dev.device = device_create(g_my_dev.class, <span class="literal">NULL</span>, g_my_dev.devno, <span class="literal">NULL</span>, NEWCHRLED_NAME);</span><br><span class="line">    <span class="keyword">if</span> (IS_ERR(g_my_dev.device))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> PTR_ERR(g_my_dev.device);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 4.打印提示信息 */</span></span><br><span class="line">    printk(<span class="string">&quot;g_my_dev: major = %d, minor = %d\r\n&quot;</span>, g_my_dev.major, g_my_dev.minor);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 驱动出口函数 */</span></span><br><span class="line"><span class="type">void</span> __exit <span class="title function_">new_char_dev_exit</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">/* 1.重新获取设备号(有可能是动态分配了的设备号) */</span></span><br><span class="line">    g_my_dev.devno = MKDEV(g_my_dev.major, g_my_dev.minor); <span class="comment">/* MKDEV宏用来将主设备号和次设备号组合成32位完整的设备号 */</span></span><br><span class="line">    <span class="comment">/* 2.删除设备节点 */</span></span><br><span class="line">    <span class="comment">/* 2.1删除设备(/dev/dev_name 将会被删除) */</span></span><br><span class="line">    device_destroy(g_my_dev.class, g_my_dev.devno);</span><br><span class="line">    <span class="comment">/* 2.2删除类 */</span></span><br><span class="line">    class_destroy(g_my_dev.class);</span><br><span class="line">    <span class="comment">/* 3.删除字符设备对象 cdev */</span></span><br><span class="line">    cdev_del(&amp;g_my_dev.mydev);</span><br><span class="line">    <span class="comment">/* 4.注销设备号(将会删除 /proc/devices 中的设备号和对应的名称记录)*/</span></span><br><span class="line">    unregister_chrdev_region(g_my_dev.devno, g_my_dev.dev_num);</span><br><span class="line">    <span class="comment">/* 5.打印卸载模块的提示信息 */</span></span><br><span class="line">    printk(<span class="string">&quot;This module is exited!\n&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/* 将上面两个函数指定为驱动的入口和出口函数 */</span></span><br><span class="line">module_init(new_char_dev_init);</span><br><span class="line">module_exit(new_char_dev_exit);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 模块信息(通过 modinfo new_char_dev 查看) */</span></span><br><span class="line">MODULE_LICENSE(<span class="string">&quot;GPL&quot;</span>);               <span class="comment">/* 源码的许可证协议 */</span></span><br><span class="line">MODULE_AUTHOR(<span class="string">&quot;qidaink&quot;</span>);            <span class="comment">/* 字符串常量内容为模块作者说明 */</span></span><br><span class="line">MODULE_DESCRIPTION(<span class="string">&quot;Description&quot;</span>);   <span class="comment">/* 字符串常量内容为模块功能说明 */</span></span><br><span class="line">MODULE_ALIAS(<span class="string">&quot;module&#x27;s other name&quot;</span>); <span class="comment">/* 字符串常量内容为模块别名 */</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h3 id="2-2-new-char-dev-h"><a href="#2-2-new-char-dev-h" class="headerlink" title="2.2 new_char_dev.h "></a><font size=3>2.2 new_char_dev.h </font></h3><details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** =====================================================</span></span><br><span class="line"><span class="comment"> * Copyright © hk. 2022-2025. All rights reserved.</span></span><br><span class="line"><span class="comment"> * File name: new_char_dev.h</span></span><br><span class="line"><span class="comment"> * Author   : qidaink</span></span><br><span class="line"><span class="comment"> * Date     : 2022-08-26</span></span><br><span class="line"><span class="comment"> * Version  :</span></span><br><span class="line"><span class="comment"> * Description:</span></span><br><span class="line"><span class="comment"> * Others   :</span></span><br><span class="line"><span class="comment"> * Log      :</span></span><br><span class="line"><span class="comment"> * ======================================================</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">#<span class="keyword">ifndef</span> __NEW_CHAR_DEV_H__</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> __NEW_CHAR_DEV_H__</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;asm/ioctl.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> MY_CHAR_MAGIC <span class="string">&#x27;k&#x27;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> MYCHAR_IOCTL_GET_MAXLEN _IOR(MY_CHAR_MAGIC, 1, int *)</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> MYCHAR_IOCTL_GET_CURLEN _IOR(MY_CHAR_MAGIC, 2, int *)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* printk和printf 打印输出的颜色定义 */</span></span><br><span class="line"><span class="comment">/* 前景色(字体颜色) */</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CLS           <span class="string">&quot;\033[0m&quot;</span>    <span class="comment">/* 清除所有颜色 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> BLACK         <span class="string">&quot;\033[1;30m&quot;</span> <span class="comment">/* 黑色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> RED           <span class="string">&quot;\033[1;31m&quot;</span> <span class="comment">/* 红色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> GREEN         <span class="string">&quot;\033[1;32m&quot;</span> <span class="comment">/* 绿色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> YELLOW        <span class="string">&quot;\033[1;33m&quot;</span> <span class="comment">/* 黄色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> BLUE          <span class="string">&quot;\033[1;34m&quot;</span> <span class="comment">/* 蓝色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> PURPLE        <span class="string">&quot;\033[1;35m&quot;</span> <span class="comment">/* 紫色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CYAN          <span class="string">&quot;\033[1;36m&quot;</span> <span class="comment">/* 青色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> WHITE         <span class="string">&quot;\033[1;37m&quot;</span> <span class="comment">/* 白色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> BOLD          <span class="string">&quot;\033[1m&quot;</span>    <span class="comment">/* 加粗字体 */</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h3 id="2-3-app-new-char-dev-c"><a href="#2-3-app-new-char-dev-c" class="headerlink" title="2.3 app_new_char_dev.c "></a><font size=3>2.3 app_new_char_dev.c </font></h3><details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** =====================================================</span></span><br><span class="line"><span class="comment"> * Copyright © hk. 2022-2025. All rights reserved.</span></span><br><span class="line"><span class="comment"> * File name: app_new_char_dev.c</span></span><br><span class="line"><span class="comment"> * Author   : qidaink</span></span><br><span class="line"><span class="comment"> * Date     : 2022-08-24</span></span><br><span class="line"><span class="comment"> * Version  :</span></span><br><span class="line"><span class="comment"> * Description: 新字符设备测试 app —— 单个次设备</span></span><br><span class="line"><span class="comment"> * Others   :</span></span><br><span class="line"><span class="comment"> * Log      :</span></span><br><span class="line"><span class="comment"> * ======================================================</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/stat.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;fcntl.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span>    <span class="comment">/* close */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/ioctl.h&gt;</span> <span class="comment">/* ioctl */</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;new_char_dev.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">/* 0.相关变量定义 */</span></span><br><span class="line">    <span class="type">int</span> fd = <span class="number">-1</span>;       <span class="comment">/* 文件描述符 */</span></span><br><span class="line">    <span class="type">int</span> max = <span class="number">0</span>;       <span class="comment">/* 驱动中缓冲区大小，驱动中为 100 字节 */</span></span><br><span class="line">    <span class="type">int</span> len = <span class="number">0</span>;       <span class="comment">/* 当前缓冲区数据字节数 */</span></span><br><span class="line">    <span class="type">char</span> buf[<span class="number">20</span>] = <span class="string">&quot;&quot;</span>; <span class="comment">/* 数据缓冲区 */</span></span><br><span class="line">    <span class="comment">/* 1.判断参数个数是否合法 */</span></span><br><span class="line">    <span class="keyword">if</span> (argc &lt; <span class="number">2</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;\n%s /dev/dev_name\n\n&quot;</span>, argv[<span class="number">0</span>]);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 2.打开字符设备 */</span></span><br><span class="line">    <span class="keyword">if</span> ((fd = open(argv[<span class="number">1</span>], O_RDWR)) &lt; <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;open %s failed\n&quot;</span>, argv[<span class="number">1</span>]);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 3.向字符设备写入数据 */</span></span><br><span class="line">    <span class="keyword">if</span> (write(fd, <span class="string">&quot;hello world!&quot;</span>, <span class="number">15</span>) &lt; <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;write failed!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 4.获取缓冲区的大小和当前数据个数 */</span></span><br><span class="line">    ioctl(fd, MYCHAR_IOCTL_GET_MAXLEN, &amp;max);</span><br><span class="line">    ioctl(fd, MYCHAR_IOCTL_GET_CURLEN, &amp;len);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;BUF_LEN = %d, curlen = %d\n&quot;</span>, max, len);</span><br><span class="line">    <span class="comment">/* 5.从字符设备读取刚才写入的数据 */</span></span><br><span class="line">    <span class="keyword">if</span> (read(fd, buf, <span class="number">15</span>) &lt; <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;read failed!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;buf = %s\n&quot;</span>, buf);</span><br><span class="line">    <span class="comment">/* 6.关闭字符设备 */</span></span><br><span class="line">    close(fd);</span><br><span class="line">    fd = <span class="number">-1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h3 id="2-4-Makefile"><a href="#2-4-Makefile" class="headerlink" title="2.4 Makefile "></a><font size=3>2.4 Makefile </font></h3><details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">##============================================================================#</span></span><br><span class="line"><span class="comment"># Copyright © hk. 2022-2025. All rights reserved.</span></span><br><span class="line"><span class="comment"># File name: Makefile</span></span><br><span class="line"><span class="comment"># Author   : qidaink</span></span><br><span class="line"><span class="comment"># Date     : 2022-08-26</span></span><br><span class="line"><span class="comment"># Version  : </span></span><br><span class="line"><span class="comment"># Description: </span></span><br><span class="line"><span class="comment"># Others   : </span></span><br><span class="line"><span class="comment"># Log      : </span></span><br><span class="line"><span class="comment">##============================================================================#</span></span><br><span class="line"><span class="comment">##</span></span><br><span class="line"><span class="comment"># 模块名和模块测试APP名称</span></span><br><span class="line">MODULE_NAME     := new_char_dev</span><br><span class="line">APP_NAME        := app_<span class="variable">$(MODULE_NAME)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># NFS 共享目录</span></span><br><span class="line">ROOTFS          ?= /home/hk/4nfs/rootfs</span><br><span class="line">MODULE_DIR      ?= <span class="variable">$(ROOTFS)</span>/01myDrivers</span><br><span class="line"></span><br><span class="line"><span class="keyword">ifeq</span> (<span class="variable">$(KERNELRELEASE)</span>,)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 选择可执行文件运行的平台</span></span><br><span class="line"><span class="keyword">ifeq</span> (<span class="variable">$(ARCH)</span>, arm)</span><br><span class="line">KERNELDIR       ?= /home/hk/5linux/linux-3.14</span><br><span class="line">GCC_TOOL        ?= arm-none-linux-gnueabi-gcc</span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">KERNELDIR       ?= /lib/modules/<span class="variable">$(<span class="built_in">shell</span> uname -r)</span>/build</span><br><span class="line">GCC_TOOL        ?= gcc</span><br><span class="line"><span class="keyword">endif</span></span><br><span class="line"></span><br><span class="line">PWD             := <span class="variable">$(<span class="built_in">shell</span> pwd)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 编译模块和测试程序</span></span><br><span class="line"><span class="section">modules:</span></span><br><span class="line">	<span class="variable">$(MAKE)</span> -C <span class="variable">$(KERNELDIR)</span> M=<span class="variable">$(PWD)</span> modules</span><br><span class="line">	<span class="variable">$(GCC_TOOL)</span> <span class="variable">$(APP_NAME)</span>.c -Wall -o <span class="variable">$(APP_NAME)</span></span><br><span class="line"></span><br><span class="line"><span class="section">modules_install:</span></span><br><span class="line">	<span class="variable">$(MAKE)</span> -C <span class="variable">$(KERNELDIR)</span> M=<span class="variable">$(PWD)</span> modules INSTALL_MOD_PATH=<span class="variable">$(ROOTFS)</span> modules_install</span><br><span class="line"></span><br><span class="line"><span class="comment"># 拷贝相关文件到nfs共享目录</span></span><br><span class="line"><span class="section">copy:</span></span><br><span class="line">	sudo cp <span class="variable">$(MODULE_NAME)</span>.ko <span class="variable">$(MODULE_DIR)</span></span><br><span class="line">	sudo cp <span class="variable">$(APP_NAME)</span> <span class="variable">$(MODULE_DIR)</span></span><br><span class="line"></span><br><span class="line"><span class="meta"><span class="keyword">.PHONY</span>: clean</span></span><br><span class="line"><span class="section">clean:</span></span><br><span class="line">	rm -rf  *.o  *.ko  .*.cmd  *.mod.*  modules.order  Module.symvers   .tmp_versions .cache.mk <span class="variable">$(APP_NAME)</span></span><br><span class="line"></span><br><span class="line"><span class="section">help:</span></span><br><span class="line">	@echo <span class="string">&quot;\033[1;32m================================ Help ================================\033[0m&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;Ubuntu may need to add sudo:&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;insmod &lt;module_name&gt;.ko   # Load module&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;rmmod &lt;module_name&gt;       # Uninstall the module&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;dmesg -C                  # Clear the kernel print information&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;lsmod                     # Check the kernel modules that have been inserted&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;dmesg                     # View information printed by the kernel&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;file &lt;module_name&gt;.ko     # View \&quot;.Ko\&quot; file information&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;make ARCH=arm             # arm platform&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;\033[1;32m======================================================================\033[0m&quot;</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">CONFIG_MODULE_SIG=n</span><br><span class="line">obj-m           += <span class="variable">$(MODULE_NAME)</span>.o</span><br><span class="line"><span class="keyword">endif</span></span><br><span class="line">    </span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h1 id="二、多个次设备"><a href="#二、多个次设备" class="headerlink" title="二、多个次设备"></a><font size=3>二、多个次设备</font></h1><h2 id="1-开发步骤-1"><a href="#1-开发步骤-1" class="headerlink" title="1. 开发步骤"></a><font size=3>1. 开发步骤</font></h2><p>多个次设备的时候步骤与单个次设备的时候其实是一样的，不同之处在于：</p>
<ul>
<li>1、设备号申请的时候要直接连续申请多个；</li>
<li>2、向内核注册新字符设备的时候，每个设备都要注册；</li>
<li>3、创建类的时候只需要创建一个；</li>
<li>4、创建设备的时候需要创建多个设备；</li>
<li>5、删除设备的时候需要删除多个；</li>
<li>6、删除字符设备对象的时候需要删除多个。</li>
</ul>
<h2 id="2-开发实例-1"><a href="#2-开发实例-1" class="headerlink" title="2. 开发实例"></a><font size=3>2. 开发实例</font></h2><h3 id="2-1-new-char-dev-multi-c"><a href="#2-1-new-char-dev-multi-c" class="headerlink" title="2.1 new_char_dev_multi.c "></a><font size=3>2.1 new_char_dev_multi.c </font></h3><details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** =====================================================</span></span><br><span class="line"><span class="comment"> * Copyright © hk. 2022-2025. All rights reserved.</span></span><br><span class="line"><span class="comment"> * File name: new_char_dev_multi.c</span></span><br><span class="line"><span class="comment"> * Author   : qidaink</span></span><br><span class="line"><span class="comment"> * Date     : 2022-08-24</span></span><br><span class="line"><span class="comment"> * Version  :</span></span><br><span class="line"><span class="comment"> * Description: 新字符设备开发框架——多个次设备</span></span><br><span class="line"><span class="comment"> * Others   :</span></span><br><span class="line"><span class="comment"> * Log      :</span></span><br><span class="line"><span class="comment"> * ======================================================</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">//=======================================================</span></span><br><span class="line"><span class="comment">/* 头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/module.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/kernel.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/fs.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/cdev.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;asm/uaccess.h&gt;</span> <span class="comment">/* copy_from_user copy_to_user  */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;linux/device.h&gt;</span>  <span class="comment">/* class_create class_destroy device_create */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;new_char_dev_multi.h&quot;</span></span></span><br><span class="line"><span class="comment">//=======================================================</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> NEWCHAR_DEV_NAME <span class="string">&quot;new_char_dev_multi&quot;</span> <span class="comment">/* 设备名称：/proc/devices文件中与该设备对应的名字，方便用户层查询主设备号 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> NEWCHAR_DEV_CNT  3                    <span class="comment">/* 次设备数量        */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> BUF_LEN          100                  <span class="comment">/* 数据读写缓冲区大小 */</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">//=======================================================</span></span><br><span class="line"><span class="comment">/** 父设备号相关结构体，为了创建子设备号(子设备 0 的设备号与父设备号相同) </span></span><br><span class="line"><span class="comment"> *  父设备可以看做是代表了整个驱动程序，父设备下挂3个具体的设备</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> _<span class="title">my_dev_parent</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="comment">/* 1.设备号与设备数量 */</span></span><br><span class="line">    <span class="type">int</span> major;   <span class="comment">/* 主设备号：占高12位，用来表示驱动程序相同的一类设备，Linux系统中主设备号范围为 0~4095 */</span></span><br><span class="line">    <span class="type">int</span> minor;   <span class="comment">/* 次设备号：占低20位，用来表示被操作的哪个具体设备 */</span></span><br><span class="line">    <span class="type">dev_t</span> devno; <span class="comment">/* 新字符设备的设备号：由主设备号和次设备号组成    */</span></span><br><span class="line">    <span class="type">int</span> dev_cnt; <span class="comment">/* 次设备数量 */</span></span><br><span class="line">    <span class="comment">/* 2.自动创建设备节点相关成员变量 */</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="keyword">class</span> *<span class="keyword">class</span>;</span> <span class="comment">/* 类（无论几个次设备，这里的类只有一个） */</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="class"><span class="keyword">struct</span> _<span class="title">my_dev_parent</span> <span class="title">parent_dev</span>=</span>&#123;</span><br><span class="line">    .major = <span class="number">200</span>,</span><br><span class="line">    .minor = <span class="number">0</span>,</span><br><span class="line">    .dev_cnt = NEWCHAR_DEV_CNT,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 新字符设备的属性 */</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">    <span class="comment">/* 1.设备号与设备数量 */</span></span><br><span class="line">    <span class="type">int</span> major;   <span class="comment">/* 主设备号：占高12位，用来表示驱动程序相同的一类设备，Linux系统中主设备号范围为 0~4095 */</span></span><br><span class="line">    <span class="type">int</span> minor;   <span class="comment">/* 次设备号：占低20位，用来表示被操作的哪个具体设备 */</span></span><br><span class="line">    <span class="type">dev_t</span> devno; <span class="comment">/* 新字符设备的设备号：由主设备号和次设备号组成 */</span></span><br><span class="line">    <span class="comment">/* 2.字符设备对象 */</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">cdev</span> <span class="title">mydev</span>;</span> <span class="comment">/* 定义一个字符设备对象设备 */</span></span><br><span class="line">    <span class="comment">/* 3.设备读写相关成员变量 */</span></span><br><span class="line">    <span class="type">char</span> mydev_buf[BUF_LEN]; <span class="comment">/* 读写缓冲区 */</span></span><br><span class="line">    <span class="type">int</span> curlen;              <span class="comment">/* 读写缓冲区中当前数据字节数 */</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 自动创建设备节点相关成员变量 */</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">device</span> *<span class="title">device</span>;</span>   <span class="comment">/* 设备 */</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span> <span class="title">g_my_dev</span>[<span class="title">NEWCHAR_DEV_CNT</span>];</span> <span class="comment">/* 定义新字符设备数组 */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//=======================================================</span></span><br><span class="line"><span class="comment">/* 新字符设备操作函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">mydev_open</span><span class="params">(<span class="keyword">struct</span> inode *pnode, <span class="keyword">struct</span> file *pfile)</span>;                                      <span class="comment">/* 打开设备 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">mydev_close</span><span class="params">(<span class="keyword">struct</span> inode *pnode, <span class="keyword">struct</span> file *pfile)</span>;                                     <span class="comment">/* 关闭设备 */</span></span><br><span class="line"><span class="type">ssize_t</span> <span class="title function_">mydev_read</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">char</span> __user *pbuf, <span class="type">size_t</span> count, <span class="type">loff_t</span> *ppos)</span>;        <span class="comment">/* 读设备 */</span></span><br><span class="line"><span class="type">ssize_t</span> <span class="title function_">mydev_write</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">const</span> <span class="type">char</span> __user *pbuf, <span class="type">size_t</span> count, <span class="type">loff_t</span> *ppos)</span>; <span class="comment">/* 写设备 */</span></span><br><span class="line"><span class="type">long</span> <span class="title function_">mydev_ioctl</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">unsigned</span> <span class="type">int</span> cmd, <span class="type">unsigned</span> <span class="type">long</span> arg)</span>;                    <span class="comment">/* 设备属性获取 */</span></span><br><span class="line"><span class="comment">/* 操作函数集定义 */</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">file_operations</span> <span class="title">myops</span> =</span> &#123;</span><br><span class="line">    <span class="comment">/* data */</span></span><br><span class="line">    .owner = THIS_MODULE,</span><br><span class="line">    .open = mydev_open,</span><br><span class="line">    .release = mydev_close,</span><br><span class="line">    .read = mydev_read,</span><br><span class="line">    .write = mydev_write,</span><br><span class="line">    .unlocked_ioctl = mydev_ioctl,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * @Function    : mydev_open</span></span><br><span class="line"><span class="comment"> * @brief       : 打开设备</span></span><br><span class="line"><span class="comment"> * @param pnode : struct inode * 类型，内核中记录文件元信息的结构体</span></span><br><span class="line"><span class="comment"> * @param pfile : struct file *  类型，读写文件内容过程中用到的一些控制性数据组合而成的对象</span></span><br><span class="line"><span class="comment"> * @return      : 0,操作完成</span></span><br><span class="line"><span class="comment"> * @Description : 函数名初始化给 struct file_operations 的成员 .open</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">mydev_open</span><span class="params">(<span class="keyword">struct</span> inode *pnode, <span class="keyword">struct</span> file *pfile)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">/* 获取 struct _my_dev g_my_dev 地址 */</span></span><br><span class="line">    pfile-&gt;private_data = (<span class="type">void</span> *)(container_of(pnode-&gt;i_cdev, <span class="keyword">struct</span> _my_dev, mydev));</span><br><span class="line">    printk(<span class="string">&quot;mydev_open is called!\n&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * @Function    : mydev_close</span></span><br><span class="line"><span class="comment"> * @brief       : 关闭设备</span></span><br><span class="line"><span class="comment"> * @param pnode : struct inode * 类型，内核中记录文件元信息的结构体</span></span><br><span class="line"><span class="comment"> * @param pfile : struct file *  类型，读写文件内容过程中用到的一些控制性数据组合而成的对象</span></span><br><span class="line"><span class="comment"> * @return      : 0,操作完成</span></span><br><span class="line"><span class="comment"> * @Description : 函数名初始化给 struct file_operations 的成员 .close</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">mydev_close</span><span class="params">(<span class="keyword">struct</span> inode *pnode, <span class="keyword">struct</span> file *pfile)</span></span><br><span class="line">&#123;</span><br><span class="line">    printk(<span class="string">&quot;mydev_close is called!\n&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * @Function    : mydev_read</span></span><br><span class="line"><span class="comment"> * @brief       : 读设备</span></span><br><span class="line"><span class="comment"> * @param pfile : struct file *  类型，指向open产生的struct file类型的对象，表示本次read对应的那次open。</span></span><br><span class="line"><span class="comment"> *                                    (读写文件内容过程中用到的一些控制性数据组合而成的对象)</span></span><br><span class="line"><span class="comment"> * @param pbuf  ：__user * 类型，指向用户空间一块内存，用来保存读到的数据。</span></span><br><span class="line"><span class="comment"> * @param count ：size_t   类型，用户期望读取的字节数。</span></span><br><span class="line"><span class="comment"> * @param ppos  ：loff_t * 类型，对于需要位置指示器控制的设备操作有用，用来指示读取的起始位置，读完后也需要变更位置指示器的指示位置。</span></span><br><span class="line"><span class="comment"> * @return      : 成功返回本次成功读取的字节数，失败返回-1</span></span><br><span class="line"><span class="comment"> * @Description : 函数名初始化给 struct file_operations 的成员 .read</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">ssize_t</span> <span class="title function_">mydev_read</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">char</span> __user *pbuf, <span class="type">size_t</span> count, <span class="type">loff_t</span> *ppos)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> size = <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span> *<span class="title">p_my_dev</span> =</span> (<span class="keyword">struct</span> _my_dev *)(pfile-&gt;private_data);</span><br><span class="line">    <span class="keyword">if</span> (count &gt; p_my_dev-&gt;curlen)</span><br><span class="line">        size = p_my_dev-&gt;curlen;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        size = count;</span><br><span class="line">    ret = copy_to_user(pbuf, p_my_dev-&gt;mydev_buf, size);</span><br><span class="line">    <span class="keyword">if</span> (ret)</span><br><span class="line">    &#123;</span><br><span class="line">        printk(<span class="string">&quot;copy to user buf failed!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">memcpy</span>(p_my_dev-&gt;mydev_buf, p_my_dev-&gt;mydev_buf + size, p_my_dev-&gt;curlen - size);</span><br><span class="line">    p_my_dev-&gt;curlen -= size;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> size;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * @Function    : mydev_write</span></span><br><span class="line"><span class="comment"> * @brief       : 写设备</span></span><br><span class="line"><span class="comment"> * @param pfile : struct file *  类型，指向open产生的struct file类型的对象，表示本次write对应的那次open。</span></span><br><span class="line"><span class="comment"> *                                    (读写文件内容过程中用到的一些控制性数据组合而成的对象)</span></span><br><span class="line"><span class="comment"> * @param pbuf  ：__user * 类型，指向用户空间一块内存，用来保存被写的数据。</span></span><br><span class="line"><span class="comment"> * @param count ：size_t   类型，用户期望写入的字节数。</span></span><br><span class="line"><span class="comment"> * @param ppos  ：loff_t * 类型，对于需要位置指示器控制的设备操作有用，用来指示写入的起始位置，写完后也需要变更位置指示器的指示位置。</span></span><br><span class="line"><span class="comment"> * @return      : 成功返回本次成功写入的字节数，失败返回-1</span></span><br><span class="line"><span class="comment"> * @Description : 函数名初始化给 struct file_operations 的成员 .write</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">ssize_t</span> <span class="title function_">mydev_write</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">const</span> <span class="type">char</span> __user *pbuf, <span class="type">size_t</span> count, <span class="type">loff_t</span> *ppos)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> size = <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span> *<span class="title">p_my_dev</span> =</span> (<span class="keyword">struct</span> _my_dev *)(pfile-&gt;private_data);</span><br><span class="line">    <span class="keyword">if</span> (count &gt; BUF_LEN - p_my_dev-&gt;curlen)</span><br><span class="line">        size = BUF_LEN - p_my_dev-&gt;curlen;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        size = count;</span><br><span class="line">    ret = copy_from_user(p_my_dev-&gt;mydev_buf + p_my_dev-&gt;curlen, pbuf, size);</span><br><span class="line">    <span class="keyword">if</span> (ret)</span><br><span class="line">    &#123;</span><br><span class="line">        printk(<span class="string">&quot;copy from user buf failed!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    p_my_dev-&gt;curlen += size;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> size;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * @Function    : mydev_ioctl</span></span><br><span class="line"><span class="comment"> * @brief       : 设备属性获取</span></span><br><span class="line"><span class="comment"> * @param pfile : struct file *  类型，指向open产生的struct file类型的对象，表示本次ioctl对应的那次open。</span></span><br><span class="line"><span class="comment"> *                                    (读写文件内容过程中用到的一些控制性数据组合而成的对象)</span></span><br><span class="line"><span class="comment"> * @param cmd   ：unsigned int  类型，用来表示做的是哪一个操作。</span></span><br><span class="line"><span class="comment"> * @param arg   ：unsigned long 类型，和cmd配合用的参数。</span></span><br><span class="line"><span class="comment"> * @return      : 成功返回0，失败返回-1</span></span><br><span class="line"><span class="comment"> * @Description : 函数名初始化给 struct file_operations 的成员 .unlocked_ioctl</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="type">long</span> <span class="title function_">mydev_ioctl</span><span class="params">(<span class="keyword">struct</span> file *pfile, <span class="type">unsigned</span> <span class="type">int</span> cmd, <span class="type">unsigned</span> <span class="type">long</span> arg)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> __user *pret = (<span class="type">int</span> *)arg;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> _<span class="title">my_dev</span> *<span class="title">p_my_dev</span> =</span> (<span class="keyword">struct</span> _my_dev *)(pfile-&gt;private_data);</span><br><span class="line">    <span class="type">int</span> maxlen = BUF_LEN;</span><br><span class="line">    <span class="keyword">switch</span> (cmd)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">case</span> MYCHAR_IOCTL_GET_MAXLEN:</span><br><span class="line">            <span class="keyword">if</span> (copy_to_user(pret, &amp;maxlen, <span class="keyword">sizeof</span>(<span class="type">int</span>)))</span><br><span class="line">            &#123;</span><br><span class="line">                printk(<span class="string">&quot;copy_to_user maxlen failed!\n&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> MYCHAR_IOCTL_GET_CURLEN:</span><br><span class="line">            <span class="keyword">if</span> (copy_to_user(pret, &amp;p_my_dev-&gt;curlen, <span class="keyword">sizeof</span>(<span class="type">int</span>)))</span><br><span class="line">            &#123;</span><br><span class="line">                printk(<span class="string">&quot;copy_to_user curlen failed!\n&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            printk(<span class="string">&quot;The cmd is unknown!\n&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 驱动入口函数 */</span></span><br><span class="line"><span class="type">int</span> __init <span class="title function_">new_char_dev_multi_init</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">/* 1.分配设备号(将会申请 parent_dev.dev_cnt 个从 0 开始的连续设备号，他们的主设备号相同，表示他们使用的是同一个驱动) */</span></span><br><span class="line">    <span class="keyword">if</span> (parent_dev.major) <span class="comment">/*  定义了设备号 */</span></span><br><span class="line">    &#123;</span><br><span class="line">        parent_dev.devno = MKDEV(parent_dev.major, <span class="number">0</span>); <span class="comment">/* MKDEV宏用来将主设备号和次设备号组合成32位完整的设备号 */</span></span><br><span class="line">        <span class="keyword">if</span> (register_chrdev_region(parent_dev.devno, parent_dev.dev_cnt, NEWCHAR_DEV_NAME))</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="comment">/* 手动指定设备号分配失败，申请自动分配设备号 */</span></span><br><span class="line">            <span class="keyword">if</span> (alloc_chrdev_region(&amp;parent_dev.devno, <span class="number">0</span>, parent_dev.dev_cnt, NEWCHAR_DEV_NAME))</span><br><span class="line">            &#123;</span><br><span class="line">                printk(<span class="string">&quot;get parent_dev failed!\n&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span>                                                                              <span class="comment">/* 未定义主设备号 */</span></span><br><span class="line">        alloc_chrdev_region(&amp;parent_dev.devno, <span class="number">0</span>, parent_dev.dev_cnt, NEWCHAR_DEV_NAME); <span class="comment">/* 申请设备号 */</span></span><br><span class="line">    parent_dev.major = MAJOR(parent_dev.devno);                                       <span class="comment">/* 获取分配号的主设备号 */</span></span><br><span class="line">    parent_dev.minor = MINOR(parent_dev.devno);                                       <span class="comment">/* 获取分配号的次设备号 */</span></span><br><span class="line">    <span class="comment">/* 2.向Linux内核注册新的字符设备 */</span></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; parent_dev.dev_cnt; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* 2.1从父设备号得到三个子设备号(子设备号是连续的) */</span></span><br><span class="line">        g_my_dev[i].devno = MKDEV(parent_dev.major, parent_dev.minor + i); <span class="comment">/* MKDEV宏用来将主设备号和次设备号组合成32位完整的设备号 */</span></span><br><span class="line">        g_my_dev[i].major = MAJOR( g_my_dev[i].devno); <span class="comment">/* 获取分配号的主设备号 */</span></span><br><span class="line">        g_my_dev[i].minor = MINOR( g_my_dev[i].devno); <span class="comment">/* 获取分配号的次设备号 */</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">/* 2.2初始化 mydev 对象, 给该对象添加操作函数集 */</span></span><br><span class="line">        cdev_init(&amp;g_my_dev[i].mydev, &amp;myops);</span><br><span class="line">        <span class="comment">/* 2.3向 Linux 系统添加字符设备 (cdev结构体变量,将会被添加到一个hash链表中) */</span></span><br><span class="line">        g_my_dev[i].mydev.owner = THIS_MODULE;</span><br><span class="line">        <span class="comment">/* 会在 /proc/devices 中创建设备号和对应的名称记录(最终只会有一条主设备号的记录，但还是要分多次添加) */</span></span><br><span class="line">        cdev_add(&amp;g_my_dev[i].mydev, g_my_dev[i].devno, <span class="number">1</span>); <span class="comment">/* 此处是固定的一个一个添加 */</span></span><br><span class="line">        <span class="comment">/* 2.4打印提示信息 */</span></span><br><span class="line">        printk(<span class="string">&quot;g_my_dev[%d]: devno=%d, major=%d, minor=%d\n&quot;</span>, i, g_my_dev[i].devno, g_my_dev[i].major, g_my_dev[i].minor);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 3.自动创建设备节点(省去 mknod 命令在 /dev 下创建设备节点步骤) */</span></span><br><span class="line">    <span class="comment">/* 3.1创建类（要注意无论是一个设备还是多个设备，类只有一个） */</span></span><br><span class="line">    parent_dev.class = class_create(THIS_MODULE, NEWCHAR_DEV_NAME);</span><br><span class="line">    <span class="keyword">if</span> (IS_ERR(parent_dev.class))</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">return</span> PTR_ERR(parent_dev.class);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 3.2创建设备(有几个次设备，就创建几个) */</span></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; parent_dev.dev_cnt; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* 创建的设备为 /dev/dev_name */</span></span><br><span class="line">        g_my_dev[i].device = device_create(parent_dev.class, <span class="literal">NULL</span>, g_my_dev[i].devno, <span class="literal">NULL</span>, <span class="string">&quot;%s%d&quot;</span>, NEWCHAR_DEV_NAME, i);</span><br><span class="line">        <span class="keyword">if</span> (IS_ERR(g_my_dev[i].device))</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">return</span> PTR_ERR(g_my_dev[i].device);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">/* 3.3打印提示信息 */</span></span><br><span class="line">        printk(<span class="string">&quot;g_my_dev[%d]: [/dev/%s%d] has been created!\n&quot;</span>, i, NEWCHAR_DEV_NAME, i);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//=======================================================</span></span><br><span class="line"><span class="comment">/* 驱动出口函数 */</span></span><br><span class="line"><span class="type">void</span> __exit <span class="title function_">new_char_dev_multi_exit</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="comment">/* 1.重新获取设备号(有可能是动态分配了的设备号) */</span></span><br><span class="line">    <span class="comment">/* 全局变量中已获取过，这里可以不再获取 */</span></span><br><span class="line">    <span class="comment">/* 2.删除设备节点 */</span></span><br><span class="line">    <span class="comment">/* 2.1删除设备(多个次设备，逐个进行删除) */</span></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; parent_dev.dev_cnt; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">/* 删除的是 /dev/dev_name */</span></span><br><span class="line">        device_destroy(parent_dev.class, g_my_dev[i].devno);</span><br><span class="line">        printk(<span class="string">&quot;g_my_dev[%d]: [/dev/%s%d] has been deleted!\n&quot;</span>, i, NEWCHAR_DEV_NAME, i);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 2.2删除类（只有一个类，删除一次即可） */</span></span><br><span class="line">    class_destroy(parent_dev.class);</span><br><span class="line">    <span class="comment">/* 3.删除字符设备对象 cdev */</span></span><br><span class="line">    <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; parent_dev.dev_cnt; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        cdev_del(&amp;g_my_dev[i].mydev);</span><br><span class="line">        <span class="comment">/* 4.注销设备号 */</span></span><br><span class="line">        <span class="comment">// unregister_chrdev_region(g_my_dev[i].devno, 1); /* 一个一个删除,这样似乎有bug，真正的主设备号并未释放，除非后边数字改成 NEWCHAR_DEV_CNT */</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 4.注销设备号（将会删除 /proc/devices 中的设备号和对应的名称记录) */</span></span><br><span class="line">    unregister_chrdev_region(parent_dev.devno, parent_dev.dev_cnt);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/* 5.打印卸载模块的提示信息 */</span></span><br><span class="line">    printk(<span class="string">&quot;This module is exited!\n&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 将上面两个函数指定为驱动的入口和出口函数 */</span></span><br><span class="line">module_init(new_char_dev_multi_init);</span><br><span class="line">module_exit(new_char_dev_multi_exit);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 模块信息(通过 modinfo new_char_dev_multi 查看) */</span></span><br><span class="line">MODULE_LICENSE(<span class="string">&quot;GPL&quot;</span>);               <span class="comment">/* 源码的许可证协议 */</span></span><br><span class="line">MODULE_AUTHOR(<span class="string">&quot;qidaink &lt;2038035593@qq.com&gt;&quot;</span>);            <span class="comment">/* 字符串常量内容为模块作者说明 */</span></span><br><span class="line">MODULE_DESCRIPTION(<span class="string">&quot;Description&quot;</span>);   <span class="comment">/* 字符串常量内容为模块功能说明 */</span></span><br><span class="line">MODULE_ALIAS(<span class="string">&quot;module&#x27;s other name&quot;</span>); <span class="comment">/* 字符串常量内容为模块别名 */</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h3 id="2-2-new-char-dev-multi-h"><a href="#2-2-new-char-dev-multi-h" class="headerlink" title="2.2 new_char_dev_multi.h "></a><font size=3>2.2 new_char_dev_multi.h </font></h3><details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** =====================================================</span></span><br><span class="line"><span class="comment"> * Copyright © hk. 2022-2025. All rights reserved.</span></span><br><span class="line"><span class="comment"> * File name: new_char_dev_multi.h</span></span><br><span class="line"><span class="comment"> * Author   : qidaink</span></span><br><span class="line"><span class="comment"> * Date     : 2022-08-26</span></span><br><span class="line"><span class="comment"> * Version  :</span></span><br><span class="line"><span class="comment"> * Description:</span></span><br><span class="line"><span class="comment"> * Others   :</span></span><br><span class="line"><span class="comment"> * Log      :</span></span><br><span class="line"><span class="comment"> * ======================================================</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">#<span class="keyword">ifndef</span> __NEW_CHAR_DEV_MULTI_H__</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> __NEW_CHAR_DEV_MULTI_H__</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;asm/ioctl.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> MY_CHAR_MAGIC <span class="string">&#x27;k&#x27;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> MYCHAR_IOCTL_GET_MAXLEN _IOR(MY_CHAR_MAGIC, 1, int *)</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> MYCHAR_IOCTL_GET_CURLEN _IOR(MY_CHAR_MAGIC, 2, int *)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* printk和printf 打印输出的颜色定义 */</span></span><br><span class="line"><span class="comment">/* 前景色(字体颜色) */</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CLS           <span class="string">&quot;\033[0m&quot;</span>    <span class="comment">/* 清除所有颜色 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> BLACK         <span class="string">&quot;\033[1;30m&quot;</span> <span class="comment">/* 黑色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> RED           <span class="string">&quot;\033[1;31m&quot;</span> <span class="comment">/* 红色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> GREEN         <span class="string">&quot;\033[1;32m&quot;</span> <span class="comment">/* 绿色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> YELLOW        <span class="string">&quot;\033[1;33m&quot;</span> <span class="comment">/* 黄色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> BLUE          <span class="string">&quot;\033[1;34m&quot;</span> <span class="comment">/* 蓝色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> PURPLE        <span class="string">&quot;\033[1;35m&quot;</span> <span class="comment">/* 紫色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> CYAN          <span class="string">&quot;\033[1;36m&quot;</span> <span class="comment">/* 青色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> WHITE         <span class="string">&quot;\033[1;37m&quot;</span> <span class="comment">/* 白色加粗字体 */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> BOLD          <span class="string">&quot;\033[1m&quot;</span>    <span class="comment">/* 加粗字体 */</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">endif</span></span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h3 id="2-3-app-new-char-dev-multi-c"><a href="#2-3-app-new-char-dev-multi-c" class="headerlink" title="2.3 app_new_char_dev_multi.c "></a><font size=3>2.3 app_new_char_dev_multi.c </font></h3><details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/** =====================================================</span></span><br><span class="line"><span class="comment"> * Copyright © hk. 2022-2025. All rights reserved.</span></span><br><span class="line"><span class="comment"> * File name: app_new_char_dev_multi.c</span></span><br><span class="line"><span class="comment"> * Author   : qidaink</span></span><br><span class="line"><span class="comment"> * Date     : 2022-08-24</span></span><br><span class="line"><span class="comment"> * Version  :</span></span><br><span class="line"><span class="comment"> * Description: 新字符设备测试 app —— 多个次设备</span></span><br><span class="line"><span class="comment"> * Others   :</span></span><br><span class="line"><span class="comment"> * Log      :</span></span><br><span class="line"><span class="comment"> * ======================================================</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/stat.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;fcntl.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span>    <span class="comment">/* close */</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/ioctl.h&gt;</span> <span class="comment">/* ioctl */</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;new_char_dev_multi.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">/* 0.相关变量定义 */</span></span><br><span class="line">    <span class="type">int</span> fd = <span class="number">-1</span>;       <span class="comment">/* 文件描述符 */</span></span><br><span class="line">    <span class="type">int</span> max = <span class="number">0</span>;       <span class="comment">/* 驱动中缓冲区大小，驱动中为 100 字节 */</span></span><br><span class="line">    <span class="type">int</span> len = <span class="number">0</span>;       <span class="comment">/* 当前缓冲区数据字节数 */</span></span><br><span class="line">    <span class="type">char</span> buf[<span class="number">20</span>] = <span class="string">&quot;&quot;</span>; <span class="comment">/* 数据缓冲区 */</span></span><br><span class="line">    <span class="comment">/* 1.判断参数个数是否合法 */</span></span><br><span class="line">    <span class="keyword">if</span> (argc &lt; <span class="number">2</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;\n%s /dev/dev_name\n\n&quot;</span>, argv[<span class="number">0</span>]);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 2.打开字符设备 */</span></span><br><span class="line">    <span class="keyword">if</span> ((fd = open(argv[<span class="number">1</span>], O_RDWR)) &lt; <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;open %s failed\n&quot;</span>, argv[<span class="number">1</span>]);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 3.向字符设备写入数据 */</span></span><br><span class="line">    <span class="keyword">if</span> (write(fd, <span class="string">&quot;hello world!&quot;</span>, <span class="number">15</span>) &lt; <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;write failed!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/* 4.获取缓冲区的大小和当前数据个数 */</span></span><br><span class="line">    ioctl(fd, MYCHAR_IOCTL_GET_MAXLEN, &amp;max);</span><br><span class="line">    ioctl(fd, MYCHAR_IOCTL_GET_CURLEN, &amp;len);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;BUF_LEN = %d, curlen = %d\n&quot;</span>, max, len);</span><br><span class="line">    <span class="comment">/* 5.从字符设备读取刚才写入的数据 */</span></span><br><span class="line">    <span class="keyword">if</span> (read(fd, buf, <span class="number">15</span>) &lt; <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;read failed!\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;buf = %s\n&quot;</span>, buf);</span><br><span class="line">    <span class="comment">/* 6.关闭字符设备 */</span></span><br><span class="line">    close(fd);</span><br><span class="line">    fd = <span class="number">-1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h3 id="2-4-Makefile-1"><a href="#2-4-Makefile-1" class="headerlink" title="2.4 Makefile "></a><font size=3>2.4 Makefile </font></h3><details class="folding-tag" blue><summary> 点击查看详情 </summary>
              <div class='content'>
              <figure class="highlight makefile"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">##============================================================================#</span></span><br><span class="line"><span class="comment"># Copyright © hk. 2022-2025. All rights reserved.</span></span><br><span class="line"><span class="comment"># File name: Makefile</span></span><br><span class="line"><span class="comment"># Author   : qidaink</span></span><br><span class="line"><span class="comment"># Date     : 2022-08-26</span></span><br><span class="line"><span class="comment"># Version  : </span></span><br><span class="line"><span class="comment"># Description: </span></span><br><span class="line"><span class="comment"># Others   : </span></span><br><span class="line"><span class="comment"># Log      : </span></span><br><span class="line"><span class="comment">##============================================================================#</span></span><br><span class="line"><span class="comment">##</span></span><br><span class="line"><span class="comment"># 模块名和模块测试APP名称</span></span><br><span class="line">MODULE_NAME     := new_char_dev_multi</span><br><span class="line">APP_NAME        := app_<span class="variable">$(MODULE_NAME)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># NFS 共享目录</span></span><br><span class="line">ROOTFS          ?= /home/hk/4nfs/rootfs</span><br><span class="line">MODULE_DIR      ?= <span class="variable">$(ROOTFS)</span>/01myDrivers</span><br><span class="line"></span><br><span class="line"><span class="keyword">ifeq</span> (<span class="variable">$(KERNELRELEASE)</span>,)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 选择可执行文件运行的平台</span></span><br><span class="line"><span class="keyword">ifeq</span> (<span class="variable">$(ARCH)</span>, arm)</span><br><span class="line">KERNELDIR       ?= /home/hk/5linux/linux-3.14</span><br><span class="line">GCC_TOOL        ?= arm-none-linux-gnueabi-gcc</span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">KERNELDIR       ?= /lib/modules/<span class="variable">$(<span class="built_in">shell</span> uname -r)</span>/build</span><br><span class="line">GCC_TOOL        ?= gcc</span><br><span class="line"><span class="keyword">endif</span></span><br><span class="line"></span><br><span class="line">PWD             := <span class="variable">$(<span class="built_in">shell</span> pwd)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 编译模块和测试程序</span></span><br><span class="line"><span class="section">modules:</span></span><br><span class="line">	<span class="variable">$(MAKE)</span> -C <span class="variable">$(KERNELDIR)</span> M=<span class="variable">$(PWD)</span> modules</span><br><span class="line">	<span class="variable">$(GCC_TOOL)</span> <span class="variable">$(APP_NAME)</span>.c -Wall -o <span class="variable">$(APP_NAME)</span></span><br><span class="line"></span><br><span class="line"><span class="section">modules_install:</span></span><br><span class="line">	<span class="variable">$(MAKE)</span> -C <span class="variable">$(KERNELDIR)</span> M=<span class="variable">$(PWD)</span> modules INSTALL_MOD_PATH=<span class="variable">$(ROOTFS)</span> modules_install</span><br><span class="line"></span><br><span class="line"><span class="comment"># 拷贝相关文件到nfs共享目录</span></span><br><span class="line"><span class="section">copy:</span></span><br><span class="line">	sudo cp <span class="variable">$(MODULE_NAME)</span>.ko <span class="variable">$(MODULE_DIR)</span></span><br><span class="line">	sudo cp <span class="variable">$(APP_NAME)</span> <span class="variable">$(MODULE_DIR)</span></span><br><span class="line"></span><br><span class="line"><span class="meta"><span class="keyword">.PHONY</span>: clean</span></span><br><span class="line"><span class="section">clean:</span></span><br><span class="line">	rm -rf  *.o  *.ko  .*.cmd  *.mod.*  modules.order  Module.symvers   .tmp_versions .cache.mk <span class="variable">$(APP_NAME)</span></span><br><span class="line"></span><br><span class="line"><span class="section">help:</span></span><br><span class="line">	@echo <span class="string">&quot;\033[1;32m================================ Help ================================\033[0m&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;Ubuntu may need to add sudo:&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;insmod &lt;module_name&gt;.ko   # Load module&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;rmmod &lt;module_name&gt;       # Uninstall the module&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;dmesg -C                  # Clear the kernel print information&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;lsmod                     # Check the kernel modules that have been inserted&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;dmesg                     # View information printed by the kernel&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;file &lt;module_name&gt;.ko     # View \&quot;.Ko\&quot; file information&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;make ARCH=arm             # arm platform&quot;</span></span><br><span class="line">	@echo <span class="string">&quot;\033[1;32m======================================================================\033[0m&quot;</span></span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">CONFIG_MODULE_SIG=n</span><br><span class="line">obj-m           += <span class="variable">$(MODULE_NAME)</span>.o</span><br><span class="line"><span class="keyword">endif</span></span><br><span class="line">    </span><br></pre></td></tr></table></figure>
              </div>
            </details>

    </div>

    
    
    

    <footer class="post-footer">




    <div>
        
            <div style="text-align:center;color: #ccc;font-size:14px;">
            ----------本文结束
            <i class="fas fa-fan fa-spin" style="color: #FF1493; font-size: 1rem"></i>
            感谢您的阅读----------
            </div>
        
    </div>





  
  <div class="my_post_copyright"> 
    <p><span>文章标题:</span><a href="/post/5a7bd00a.html">LV10-02-字符设备驱动-04-字符设备开发实例</a></p>
    <p><span>文章作者:</span><a href="/" title="欢迎访问 《苏木》 的学习笔记">苏木</a></p>
    <p><span>发布时间:</span>2023年07月08日 - 18:58</p>
    <p><span>最后更新:</span>2025年06月14日 - 00:25</p>
    <p><span>原始链接:</span><a href="/post/5a7bd00a.html" title="LV10-02-字符设备驱动-04-字符设备开发实例">https://sumumm.github.io/post/5a7bd00a.html</a></p>
    <p><span>许可协议:</span><i class="fab fa-creative-commons"></i> <a rel="license" href= "https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
  </div>
  


          <div class="post-tags">
              <a href="/tags/LV10-%E9%A9%B1%E5%8A%A8%E5%BC%80%E5%8F%91/" rel="tag"><i class="fa fa-tag"></i> LV10-驱动开发</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/4ba17eea.html" rel="prev" title="LV10-03-IO模型-01-驱动中的IO模型">
                  <i class="fa fa-angle-left"></i> LV10-03-IO模型-01-驱动中的IO模型
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/725b18b.html" rel="next" title="LV10-02-字符设备驱动-03-工作原理与开发流程">
                  LV10-02-字符设备驱动-03-工作原理与开发流程 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2017 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">苏木</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">3.7m</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">225:26</span>
  </span>
</div>




    <span id="sitetime"></span>
    <script defer language=javascript>
        function siteTime()
        {
            window.setTimeout("siteTime()", 1000);
            var seconds = 1000;
            var minutes = seconds * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var today = new Date();
            var todayYear = today.getFullYear();
            var todayMonth = today.getMonth()+1;
            var todayDate = today.getDate();
            var todayHour = today.getHours();
            var todayMinute = today.getMinutes();
            var todaySecond = today.getSeconds();
            /*==================================================
            Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
            year        - 作为date对象的年份，为4位年份值
            month       - 0-11之间的整数，做为date对象的月份
            day         - 1-31之间的整数，做为date对象的天数
            hours       - 0(午夜24点)-23之间的整数，做为date对象的小时数
            minutes     - 0-59之间的整数，做为date对象的分钟数
            seconds     - 0-59之间的整数，做为date对象的秒数
            microseconds - 0-999之间的整数，做为date对象的毫秒数
            ==================================================*/
            var t1 = Date.UTC(2017, 
                              5, 
                              19, 
                              0, 
                              0, 
                              0); //北京时间
            var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
            var diff = t2-t1;
            var diffYears = Math.floor(diff/years);
            var diffDays = Math.floor((diff/days)-diffYears*365);
            var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
            var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
            var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
            document.getElementById("sitetime").innerHTML="已在这里 "+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
        }
        siteTime();
    </script>



    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.umd.js" integrity="sha256-ytMJGN3toR+a84u7g7NuHm91VIR06Q41kMWDr2pq7Zo=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>


  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


 
        <div id="click-show-text"
            data-mobile = false
            data-text = 富强,民主,文明,和谐,自由,平等,公正,法制,爱国,敬业,诚信,友善
            data-fontsize = 15px
            data-random= false>
        </div>
       

      
        <script async src=https://cdn.jsdelivr.net/npm/hexo-next-mouse-effect@latest/click/showText.js></script>
      

      
    




    <script async src="/js/fancybox_param.js"></script>





<!-- APlayer本体 -->



</body>
</html>
